﻿global using System.Text;

using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Routing;

using System.Text.Encodings.Web;

namespace WXWorkSvc.Common.Extensions;

public static class TagHelperExtensions
{
    //public static string GetLinkString(this IHtmlGenerator htmlGenerator, ViewContext viewContext, string linkText, string pageName, string cssClass, Dictionary<string, string> routeValues, string? pageHandler)
    //{
    //    return htmlGenerator.GeneratePageLink(viewContext, linkText, pageName, pageHandler, null, null, null, routeValues, string.IsNullOrEmpty(cssClass) ? null : new { @class = cssClass }).GetHtmlString();
    //}
    public static void AddHtmlTooltip(this TagBuilder tag, ModelMetadata metadata, string placement = "right")
    {
        tag.InnerHtml.AppendHtml(metadata.GetDisplayName());
        if (!string.IsNullOrEmpty(metadata.Description))
        {
            tag.Attributes.Add("data-bs-title", metadata.Description);
            tag.Attributes.Add("data-bs-toggle", "tooltip");
            tag.Attributes.Add("data-bs-placement", placement);
        }
    }
    
    public static string GetDisplayName(this ModelExpression modelExpression)
    {
        return string.IsNullOrEmpty(modelExpression.Metadata.DisplayName) ? modelExpression.Metadata.PropertyName ?? "" : modelExpression.Metadata.DisplayName;
    }



   
    public static string GetHtmlString(this TagBuilder tagBuilder)
    {
        if (tagBuilder is null)
            return "";
        StringBuilder sb = new();
        StringWriter sw = new StringWriter(sb);
        tagBuilder.WriteTo(sw, HtmlEncoder.Default);
        return sb.ToString();
    }
    public static string GetHtmlString(this TagHelperOutput output)
    {
        StringBuilder sb = new();
        var sw = new StringWriter(sb);
        output.WriteTo(sw, NullHtmlEncoder.Default);
        return sb.ToString();
    }

    /// <summary>
    /// 错误汇总，排除model的属性的错误
    /// 当没有错误的时候，返回空
    /// </summary>
    /// <param name="generator"></param>
    /// <param name="viewContext"></param>
    /// <returns></returns>
    public static TagBuilder GenerateValidationSummary(this IHtmlGenerator generator, ViewContext viewContext)
    {
        return generator.GenerateValidationSummary(viewContext, true, null, "div", new { @class = "text-danger" });
    }

     
}
